import 'dart:convert';

/// 根据服务器接口返回格式统一标准的BaseResponse
class BaseResponse<T> {
  //  消息
  String? msg;

  bool? success = false;

  //  自定义code
  int? code;

  //  接口返回的数据
  T? result;
  T? page;
  BaseResponse({
    this.msg,
    this.success,
    this.code,
    this.result,
    this.page,
  });
  BaseResponse.fromJson(dynamic json) {
    if (json is Map<String, dynamic>) {
      if (json['result'] != null && json['result'] != 'null') {
        result = json['result'];
      }
      if (json['page'] != null && json['page'] != 'null') {
        page = json['page'];
      }
      code = json['code'];
      msg = json['msg'];
      success = json['success'];
    } else {
      msg = '数据异常';
      success = false;
    }
  }

  @override
  String toString() {
    StringBuffer sb = StringBuffer('{');
    sb.write("\"message\":\"$msg\"");
    sb.write(",\"code\":$code");
    sb.write(",\"success\":$success");
    sb.write(",\"page\":$page");
    sb.write(",\"result\":${json.encode(result)}");
    sb.write('}');
    return sb.toString();
  }
}

class PageModel {
  int? page;
  int? pages;
  int? size;
  int? total;

  PageModel.fromJson(Map<String, dynamic> json) {
    page = json['page'];
    pages = json['pages'];
    size = json['size'];
    total = json['total'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['page'] = page;
    data['pages'] = pages;
    data['size'] = size;
    data['total'] = total;
    return data;
  }
}

class BaseResponseCode {
  /// 成功
  static const int success = 200;

  /// 错误
  static const int error = 1;

  /// 更多
}

/// 异常处理
class ErrorEntity implements Exception {
  int? code;
  String? errorMessage;

  ErrorEntity({this.code, this.errorMessage});

  @override
  String toString() {
    if (errorMessage == null) return "Exception";
    return 'ErrorEntity{code: $code, errorMessage: $errorMessage}';
  }
}
